package se.jayway.millionaire.dao.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import se.jayway.millionaire.dao.Solution;
import se.jayway.millionaire.dao.SolutionDAO;


public class SolutionDAOImpl extends SolutionDAO {
	
	private final File file;
	private List<Solution> solutions;
	private int currentSolutionIndex;

	public SolutionDAOImpl(File file) {
		this.file = file;
	}
	
	public void populate() {
		InputStream in = null;
		try {
			in = new FileInputStream(file);
			if (in == null) {
				throw new IllegalStateException("Missing database.properties file in classpath");
			}
			Properties database = new Properties();
			database.load(in);
			parse(database);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) { 
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private void parse(Properties database) {
		solutions = new ArrayList<Solution>();
		int solutionIndex = 1;
		Solution solution = assembleSolution(database, solutionIndex);
		while (solution != null) {
			solutions.add(solution);
			solutionIndex++;
			solution = assembleSolution(database, solutionIndex);
		}
	}

	private Solution assembleSolution(Properties database, int solutionIndex) {
		String questionText = database.getProperty(solutionIndex + ".question");
		if (questionText == null) {
			return null;
		}

		List<String> answerAlternatives = new ArrayList<String>();
		for (int answerIndex = 1; answerIndex < 5; answerIndex++) {
			String answerText = database.getProperty(solutionIndex + ".answer." + answerIndex);
			answerAlternatives.add(answerText);
		}

		int correctAnswerIndex = Integer.parseInt(database.getProperty(solutionIndex + ".correct")) - 1;

		return new Solution(questionText,
				answerAlternatives.toArray(new String[answerAlternatives.size()]),
				answerAlternatives.get(correctAnswerIndex - 1));
	}

	public Solution nextSolution() {
		if (solutions == null) {
			throw new IllegalStateException("SolutionDAO not populated");
		}
		Solution solution = solutions.get(currentSolutionIndex);
		currentSolutionIndex = (currentSolutionIndex + 1) % solutions.size();
		return solution;
	}
}
